﻿using System;
using System.Windows.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using J2i.Net.Ntp;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Notification;
using System.Text;
using System.IO;
using System.Net.Sockets;

namespace Synchronize
{
    public partial class MainPage : PhoneApplicationPage
    {
        static public NtpClient _ntpClient;
        bool setnewtime = false;
        int counter_refresh = 0;

        // это таймер обновления плитки
        ShellTileSchedule SampleTileSchedule = new ShellTileSchedule();

        public static IsolatedStorageSettings settings;

        public static int server_ntp
        {
            get
            {
                return GetValueOrDefault<int>("server_ntp", 0);
            }
            set
            {
                if (AddOrUpdateValue("server_ntp", 0))
                {
                    settings.Save();
                }
            }
        }

        public string[] NtpServerList = new string[]
        {
            "ntp.mobatime.ru",
            "time-a.nist.gov",
            "pool.ntp.org ",
            "asia.pool.ntp.org",
            "europe.pool.ntp.org",
            "north-america.pool.ntp.org",
            "oceania.pool.ntp.org",
            "south-america.pool.ntp.org",
        };

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            settings = IsolatedStorageSettings.ApplicationSettings;

            _ntpClient = new NtpClient(NtpServerList[server_ntp]);
            _ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);

            // при старте запросим точное время
            _ntpClient.RequestTime();

            DispatcherTimer systimer = new DispatcherTimer();
            systimer.Interval = TimeSpan.FromSeconds(1);
            systimer.Tick += SysTimeTick;
            systimer.Start();
        }

        private void HandleResponse(IAsyncResult asyncResult)
        {

        }

        public class HttpWebUpdateState
        {
            public WebRequest AsyncRequest { get; set; }
            public WebResponse AsyncResponse { get; set; }
        }

        void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
        {
        }

        void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
        {
        }

        // сохранение параметров
        public static bool AddOrUpdateValue(string Key, Object value)
        {
            bool valueChanged = false;

            // If the key exists
            if (settings.Contains(Key))
            {
                // If the value has changed
                if (settings[Key] != value)
                {
                    // Store the new value
                    settings[Key] = value;
                    valueChanged = true;
                }
            }
            // Otherwise create the key.
            else
            {
                settings.Add(Key, value);
                valueChanged = true;
            }
            return valueChanged;
        }

        public static T GetValueOrDefault<T>(string Key, T defaultValue)
        {
            T value;

            // If the key exists, retrieve the value.
            if (settings.Contains(Key))
            {
                value = (T)settings[Key];
            }
            // Otherwise, use the default value.
            else
            {
                value = defaultValue;
            }
            return value;
        }

        void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(() =>
            {
                TimeHour.Text = _ntpClient.GetCurrentTime().ToLocalTime().Hour.ToString("D2");
                TimeMinute.Text = _ntpClient.GetCurrentTime().ToLocalTime().Minute.ToString("D2");
                TextSecond.Text = _ntpClient.GetCurrentTime().ToLocalTime().Second.ToString("D2");

                if (setnewtime == true)
                {  // установка системного времени
                    //System.SetTime
                    //DateTime.Now = _ntpClient.GetCurrentTime();
                }
                else
                {
                    // запутим таймер с точным временем
                    DispatcherTimer timer = new DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(1);
                    timer.Tick += dispatcherTimer_Tick;
                    timer.Start();
                }

            });
        }

        private void SysTimeTick(object sender, EventArgs e)
        {
            SystemTime.Text = DateTime.Now.ToLocalTime().ToString();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            _ntpClient.RequestTime();
        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            _ntpClient.IncrementCurrentTime();

            TimeHour.Text = _ntpClient.GetCurrentTime().ToLocalTime().Hour.ToString("D2");
            TimeMinute.Text = _ntpClient.GetCurrentTime().ToLocalTime().Minute.ToString("D2");
            TextSecond.Text = _ntpClient.GetCurrentTime().ToLocalTime().Second.ToString("D2");

            if (counter_refresh++ == 60)
            {  // каждую минуту обновляем время
                counter_refresh = 0;
                setnewtime = true;
                _ntpClient.RequestTime();
            }
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        { // подводка часов телефона
            setnewtime = true;
            _ntpClient.RequestTime();
        }

        private void Server_Click(object sender, RoutedEventArgs e)
        { // выбор сервера точного времени
            this.NavigationService.Navigate(new Uri("/Servers.xaml", UriKind.Relative));
        }

        private void Correct_Click(object sender, RoutedEventArgs e)
        {

        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }
    }


}